const { get, post } = require('../../../utils/request.js')
const { baseUrl } = require('../../../utils/config.js')
const { shared, timing, Easing, runOnJS } = wx.worklet;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: baseUrl,
    list: [],
    tempList: [
      { remindTypeName: '生日', icon: 'icon2.png' },
      { remindTypeName: '纪念日', icon: 'icon1.png' },
      { remindTypeName: '信用卡', icon: 'icon6.png' },
      { remindTypeName: '汽车保养', icon: 'icon4.png' },
      { remindTypeName: '食品到期', icon: 'icon5.png' },
    ],
    directionFlag: {},
    remindTypeName: '',
    fixMoneyData: [],
    fixMoneyAnimal: [],
    activeCount: 0,
    actionWordCss: 'show-action-icon',
    actionIconCss: 'hiden-action-icon',
    defaultHeight: 70,
    bottomIconHeight: 70,
    inputFocus: false,
    showIconBanner: false,
    choosedIcon: 'type93.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.directionFlag = shared(0);
    this.fresh();
  },

  fresh() {
    get('remindtype/types', null, (data) => {
      if (data && data.length > 0) {
        const count = data.filter(p => p.isActive).length;
        this.setData({
          list: data,
          activeCount: count
        })
      }
      this.initDepositData(this.data.list)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  clickDown({ currentTarget: { dataset: { index } } }) {
    if (index < this.data.list.length - 1) {
      const temp = this.data.list[index];
      this.changePositionSort(temp.id, temp.sort, 'down', (data) => {
        wx.redirectTo({
          url: '/pages/remind/remindType/remindType'
        })
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        prevPage.onLoad();
      });
    }
  },
  clickUp({ currentTarget: { dataset: { index } } }) {
    if (index > 0) {
      const temp = this.data.list[index];
      this.changePositionSort(temp.id, temp.sort, 'up', (data) => {
        wx.redirectTo({
          url: '/pages/remind/remindType/remindType'
        })
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        prevPage.onLoad();
      });
    }
  },
  onCloseTypeItem({ currentTarget: { dataset: { index, fix } } }) {
    const durationTime = fix ? 100 : 300;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);
    if (this.data.fixMoneyData[index].cardOpened) {
      const child = this.data.fixMoneyAnimal[index];
      this.data.fixMoneyData[index].cardOpened = false
      child.cardX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
      child.actionX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
    }

  },
  onGestureEvent(e) {
    'worklet'
    const { deltaX, state, currentTarget: { dataset: { index, fix } } } = e;

    const child = this.data.fixMoneyAnimal[index];
    const tempX = child.cardX.value + deltaX;
    const cardOpenX = fix ? -80 : -165;
    const actionOpenX = -5;
    const durationTime = fix ? 300 : 500;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);

    if (deltaX > 0) {
      this.data.directionFlag.value = 1;
    } else if (deltaX < 0) {
      this.data.directionFlag.value = -1;
    }

    if (state == 2) {
      if (tempX > 0) {
        child.cardX.value = 0;
        child.actionX.value = 0;
      } else {
        let calculateX = deltaX;
        if (child.cardX.value < cardOpenX) {
          const n1 = Math.abs(child.cardX.value + deltaX) + cardOpenX;
          calculateX = deltaX * (1 - n1 * 1.0 / 50)
        }

        child.cardX.value += calculateX;
        child.actionX.value += child.actionX.value < actionOpenX ? calculateX * 0.3 : calculateX * 0.1;

      }
    } else if (state == 3) {
      if (this.data.directionFlag.value > 0) {
        runOnJS(this.updateFixMoney)(index, false)

        child.cardX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.actionX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
      } else {
        runOnJS(this.updateFixMoney)(index, true);

        child.cardX.value = timing(cardOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });

        child.actionX.value = timing(actionOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
      }
    }
  },
  initDepositData(data) {
    const deposits = data;
    const temp = []

    deposits.forEach((item) => {
      temp.push({
        id: item.id,
        cardX: shared(0),
        actionX: shared(0)
      })
    })

    this.setData({
      fixMoneyData: deposits,
      fixMoneyAnimal: temp
    })

    this.data.fixMoneyAnimal.forEach((item, index) => {
      item.cardX.value = 0;
      item.actionX.value = 0;

      this.applyAnimatedStyle(`.card-index-${item.id}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.cardX.value}px)`,
        };
      });
    })


  },
  clearAnimal() {
    this.data.fixMoneyAnimal.forEach((item, index) => {
      this.clearAnimatedStyle(`.card-index-${index}`, [], () => {
        console.log('animatedStyle 已清除绑定')
      })
    })
  },
  updateFixMoney(index, openedFlag) {
    this.data.fixMoneyData[index].cardOpened = openedFlag
  },
  submitAddRemindType({ detail: { value } }) {
    const icon = this.data.choosedIcon;
    if (value && value.length > 0) {
      get('remindtype/addTaskType', { name: value, icon: icon }, () => {
        this.setData({
          remindTypeName: '',
          choosedIcon: 'type93.png',
          bottomIconHeight: 90
        })
        wx.redirectTo({
          url: '/pages/remind/remindType/remindType'
        })
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        prevPage.onLoad();
      })
    }

  },

  afterRemoveType(id) {
    const item = this.data.list.splice(id, 1);
    this.setData({
      list: this.data.list,
      remindTypeName: ''
    })
    this.initDepositData(this.data.list);
    get(`remindtype/delete/${item[0].id}`, null, () => {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.onLoad();
    })
  },

  removeRemindType({ currentTarget: { id } }) {
    const afterRemoveType = this.afterRemoveType.bind(this);
    wx.showModal({
      title: '提示',
      content: '确定删除？',
      success(res) {
        if (res.confirm) {
          afterRemoveType(id);
        }
      }
    })

  },
  disableRemindType({ currentTarget: { id, dataset: { active } } }) {
    get(`remindtype/disable/${this.data.list[id].id}`, { active: active }, () => {
      wx.redirectTo({ url: '/pages/remind/remindType/remindType' })
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.onLoad();
    })

  },
  changePositionSort(id, sort, position, callback) {
    get('remindtype/change/sort', {
      id: id,
      sort: sort,
      position: position
    }, (data) => {
      if (callback) {
        callback(data)
      }
    })
  },
  changeInputType() {
    const temp = this.data.actionWordCss;
    if (this.data.actionIconCss == 'show-action-icon') {
      this.setData({
        bottomIconHeight: 360,
        showIconBanner: true
      })
      wx.hideKeyboard({
        complete(res) {
          console.log(res)
        }
      })
    } else {
      this.setData({
        inputFocus: true
      })
    }
    this.setData({
      actionWordCss: this.data.actionIconCss,
      actionIconCss: temp
    })

  },
  onFocusInput({ detail: { height } }) {
    if (height > 0) {
      this.setData({
        actionWordCss: 'hiden-action-icon',
        actionIconCss: 'show-action-icon',
        inputFocus: true,
        showIconBanner: false,
        bottomIconHeight: height + 64
      })
    }
    

  },
  onClickList() {
    wx.hideKeyboard()
    this.setData({
      bottomIconHeight: this.data.defaultHeight,
      showIconBanner: false
    })
  },
  shooseIt({ currentTarget: { dataset: { icon } } }) {
    this.setData({
      choosedIcon: icon
    })
  }

})